import React, { PureComponent } from 'react';
import _ from 'lodash';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Select, Input, Checkbox, Tooltip, Spin, message } from 'antd';
import {
  PrimaryGhostC,
  FirstHeaderC,
  SecondHeaderC,
  UploadC,
  FormGroup,
  AdvancedSearch,
  FixedButtonC,
  NormalCardC,
  IconC,
  SingleDateC,
  PrimaryC,
  TableC,
  InputC,
  TradingMarketC,
  InputNumberC,
} from '../../../comps';
import config from '../../../comps/business/tradingMarket/config';
// const FormItem = Form.Item;
import { connect } from 'dva';
import moment from 'moment';
import accounting from 'accounting';
import config1 from '../../../utils/tableMoreIdConfig';
import { VTComponents, VTScroll } from 'virtualizedtableforantd';
// valuateAnalysis:{   //系统管理 - 业务参数维护 - 资产管理计划维护 - 估值解析
//     valuateAnalysisTable: 8
// }
const {
  valuateAnalysis: { valuateAnalysisTable },
} = config1;
@Form.create()
@connect(({ OutsourceInvestMsgMaintainM, loading, userM: user }) => ({ OutsourceInvestMsgMaintainM, loading, user }))
export default class valuateAnalysisInfoTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      editRow: undefined,
      columns: [
        {
          title: '底层资产行内资产/负债编码',
          dataIndex: 'assetDebtCode',
          key: 'assetDebtCode',
        },
        {
          title: '证券名称',
          dataIndex: 'secuabbr',
          key: 'secuabbr',
        },
        {
          title: '交易市场',
          dataIndex: 'exchangeCode',
          key: 'exchangeCode',
        },
        {
          title: '底层资产持仓数量',
          dataIndex: 'bottomPositionNum',
          key: 'bottomPositionNum',
        },
        {
          title: '底层资产折算人民币市值',
          dataIndex: 'bottomAssetRMBValue',
          key: 'bottomAssetRMBValue',
        },
        {
          title: '持仓日期',
          dataIndex: 'positionDate',
          key: 'positionDate',
        },
      ],
      dataSource: [],
    };
  }
  componentDidMount() {}
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.dataSource) !== JSON.stringify(this.props.dataSource)) {
      this.setState({
        columns: nextProps.columns,
        dataSource: nextProps.dataSource,
        editRow: undefined,
      });
      this.props.onChange(nextProps.dataSource);
    }
  }

  add = () => {
    const { dataSource, editRow } = this.state;

    if (editRow) return;
    const row = {
      id: Math.round(Math.random() * 10000000),
      editType: 'add', //记录是新增还是编辑
    };
    this.setState({
      editRow: row,
      dataSource: [
        {
          ...row,
          isEdit: true,
        },
        ...dataSource,
      ],
    });
  };

  // 保存
  saveItem = (e) => {
    const { dataSource, editRow } = this.state;
    const { form } = this.props;
    const { getFieldsValue, validateFields } = form;
    // const values = getFieldsValue() || {}
    validateFields((err, values) => {
      if (err) return;
      let t = dataSource.find((x) => {
        if (x.assetDebtCode == values.assetDebtCode && x.exchangeCode == values.exchangeCode && x.isEdit != true) return true;
      });

      if (t) {
        message.warning('有重复证券');
        return;
      }
      this.setState(
        {
          dataSource: dataSource.map((x) => {
            if (x.id == editRow.id) {
              return { id: editRow.id, ...values, positionDate: values.positionDate?.format('YYYY-MM-DD') };
            } else {
              return x;
            }
          }),
          editRow: undefined,
        },
        () => {
          this.props.onChange(this.state.dataSource);
        },
      );
    });
  };
  // 取消
  cancelItem = (e) => {
    const { dataSource, editRow } = this.state;
    const { form } = this.props;

    this.setState({
      dataSource:
        editRow?.editType == 'add'
          ? dataSource.filter((x) => x.id != editRow.id)
          : dataSource.map((x) => {
              if (x.id == editRow.id) {
                const { isEdit, ...other } = x;
                return other;
              }
              return x;
            }),
      editRow: undefined,
    });
    form.resetFields();
  };

  //编辑
  editItem = (row) => {
    const { dataSource, editRow } = this.state;
    const { form } = this.props;
    const { getFieldsValue, setFieldsValue } = form;
    if (editRow) {
      message.warning('有正在编辑中的证券，请保存后再进行操作');
      return;
    }

    this.setState(
      {
        editRow: row,
        dataSource: dataSource.map((x) => {
          if (row.id == x.id) {
            return {
              ...row,
              isEdit: true,
            };
          } else {
            return x;
          }
        }),
      },
      () => {
        setFieldsValue({ ...row, positionDate: moment(row.positionDate) });
      },
    );
    // this.setState(({dataSource})=>{
    //     columns: undefined,
    //     dataSource: undefined,
    // })
  };
  //删除
  deleteItem = (row) => {
    const { dataSource, editRow } = this.state;
    if (editRow) {
      message.warning('有正在编辑中的证券，请保存后再进行操作');
      return;
    }

    this.setState(
      {
        dataSource: dataSource.filter((x) => x.id != row.id),
      },
      () => {
        this.props.onChange(this.state.dataSource);
      },
    );
  };
  render() {
    // const { data } = this.state
    const { columns, dataSource, editRow = {} } = this.state;

    if (columns?.length && columns[columns?.length - 1].title != '操作' && this.props.type == 1) {
      columns.push({
        title: '操作',
        width: 100,
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        operates: [],
      });
    }

    const newColumns = columns?.map((x) => {
      // 底层资产行内资产/负债编码
      if (x.key == 'assetDebtCode') {
        return {
          ...x,
          title: (
            <span>
              {x.title}
              <Tooltip title={'穿透证券代码'}>
                <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
              </Tooltip>
            </span>
          ),
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputC
                  form={this.props.form} // form对象
                  dataIndex={'assetDebtCode'}
                  rules={[{ required: true, message: '请输入底层资产行内资产/负债编码' }]}
                  max={40}
                />
              );
            } else {
              return text || '--';
            }
          },
        };
      }
      // 证券名称
      if (x.key == 'secuabbr') {
        return {
          ...x,
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputC
                  form={this.props.form} // form对象
                  dataIndex={'secuabbr'}
                  rules={[{ required: true, message: '请输入证券名称' }]}
                  // max={40}
                />
              );
            } else {
              return text || '--';
            }
          },
        };
      }
      // 交易市场
      if (x.key == 'exchangeCode') {
        return {
          ...x,
          width: '200',
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <TradingMarketC
                  positionBody={true}
                  form={this.props.form} // form对象
                  title=''
                  dataIndex={'exchangeCode'}
                  marketType={['jys', 'yhj', 'cw']}
                  width={170}
                  rules={[{ required: true, message: '请选择交易市场' }]}
                />
              );
            } else {
              return (
                config.filter((item) => {
                  return item.value == text;
                })[0]?.title || '--'
              );
            }
          },
        };
      }
      // 底层资产持仓数量
      if (x.key == 'bottomPositionNum') {
        return {
          ...x,
          title: (
            <span>
              {x.title}
              <Tooltip
                title={
                  '依据《资产价格 估值报送单位规范》，股票数量即代表总股数，基金的数量即代表持有份额等；对于现金和银行存款类、同业存单类、 拆放同业及债券买入返售 类、债券类、非标准化债权类、金融衍生品、代客境外理财投资 QDII （非净值型）以及其他金融资产和负债，数量即为元为单位的金额'
                }
              >
                <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
              </Tooltip>
            </span>
          ),
          type: 'money',
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputNumberC
                  form={this.props.form} // form对象
                  dataIndex={'bottomPositionNum'}
                  precision={5}
                  max={999999999999}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入底层资产持仓数量' }]}
                />
              );
            } else {
              return `${text ? accounting.formatNumber(Number(text), 5) : '--'}`;
            }
          },
        };
      }

      // 底层资产折算人民币市值
      if (x.key == 'bottomAssetRMBValue') {
        return {
          ...x,
          type: 'money',
          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <InputNumberC
                  form={this.props.form} // form对象
                  dataIndex={'bottomAssetRMBValue'}
                  precision={2}
                  max={999999999999}
                  unit={'元'}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入底层资产折算人民币市值' }]}
                />
              );
            } else {
              return `${text ? accounting.formatNumber(Number(text), 2) : '--'}`;
            }
          },
        };
      }
      // 持仓日期
      if (x.key == 'positionDate') {
        return {
          ...x,
          title: (
            <span>
              {x.title}
              <Tooltip title={'估值表日期'}>
                <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
              </Tooltip>
            </span>
          ),

          render: (text, record) => {
            if (record.id == editRow.id) {
              return (
                <SingleDateC
                  form={this.props.form} // form对象
                  dataIndex={'positionDate'}
                  disabled={true}
                  initialValue={moment(this.props.date)}
                />
              );
            } else {
              return text || '--';
            }
          },
        };
      }
      if (x.key == 'operate') {
        return {
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          width: 100,
          type: 'operate',
          operates: [
            {
              title: '保存',
              onClick: (record, index) => {
                this.saveItem(record);
              },
              rules: {
                // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
              },
            },
            {
              title: '取消',
              onClick: (record, index) => {
                this.cancelItem(record);
              },
              rules: {
                // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
              },
            },
            {
              title: '编辑',
              onClick: (record, index) => {
                this.editItem(record);
              },
              rules: {
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['!='] }] },
              },
            },
            {
              title: '删除',
              onClick: (record, index) => {
                this.deleteItem(record);
              },
              rules: {
                hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['!='] }] },
              },
            },
          ],
        };
      }

      return x;
    });

    return (
      <>
        {this.props.type == 1 && <PrimaryC title='新增' onClick={() => this.add()} />}
        <div style={{ marginTop: '20px' }}>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            rowKey='id'
            hidePage={true}
            scroll={{ x: '100%', y: '500px' }}
            components={VTComponents({
              id: valuateAnalysisTable,
              destroy: true,
            })}
            // onChange={this.handleTableChange}
          />
        </div>
      </>
    );
  }
}
